package com.weijing.pretty_app.activity

import android.animation.ValueAnimator
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.ActivityNenFuHomeBinding
import com.weijing.pretty_app.fragment.UserModel
import com.weijing.pretty_app.models.SelectModel
import com.weijing.pretty_app.util.BluetoothSocketManager
import com.weijing.pretty_app.util.CoreUtil
import com.weijing.pretty_app.util.HalfCircleSeekBar
import com.weijing.pretty_app.util.HexConverter
import com.weijing.pretty_app.util.HexDataParse
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.SPUtil
import com.weijing.pretty_app.util.ToastUtils
import com.weijing.pretty_app.util.UserRepository
import com.weijing.pretty_app.util.WorkTimerController
import java.util.Locale

private const val TAG = "NenFuHomeActivity"

/**
 * 嫩肤主页面
 */
class NenFuHomeActivity : BaseActivity() {

    private val binding by lazy { ActivityNenFuHomeBinding.inflate(layoutInflater) }
    override fun getMainView(): View = binding.main

    private var leftUserModel: UserModel? = null
    private var rightUserModel: UserModel? = null
    private var seekBarMax1L = 100
    private var seekBarMin1L = 0
    private var seekBarMax2L = 100
    private var seekBarMin2L = 0
    private var seekBarMax3L = 10
    private var seekBarMin3L = 1
    private var seekBarMax1R = 100
    private var seekBarMin1R = 0
    private var seekBarMax2R = 100
    private var seekBarMin2R = 0
    private var seekBarMax3R = 10
    private var seekBarMin3R = 1

    // 用于保存每个容器对应的呼吸动画，便于后续取消动画
    private val breathingAnimators = mutableMapOf<View, ValueAnimator>()
    private val controllers = mutableMapOf<String, WorkTimerController>()
    private var actionFlagL = 0 //待机 0 ，准备1，输出2
    private var actionFlagR = 0 //待机 0 ，准备1，输出2
    private var receiveFlagL = 0 //接收待机状态 01/02/03(待机/准备/输出)
    private var receiveFlagR = 0 //接收待机状态 01/02/03(待机/准备/输出)
    private var mWorkCountL = 0 //计时器计算的手柄运行次数
    private var mWorkCountR = 0 //计时器计算的手柄运行次数

    private val dataListener: (data: ByteArray) -> Unit = { data ->
        val receivedText = HexConverter.byteArrayToHexString(data) // 默认是 ASCII 格式
        Log.d(TAG, "收到蓝牙数据: $receivedText")
        HexDataParse.parseHexString(receivedText) { funcCode, hexData ->
            Log.i(TAG, "接收到的转化数据-- $hexData")
            when (funcCode) {
                KeyUtil.E7 -> {   //最大值和最小值
                    Log.i(TAG, "功能码 E7 数据：$hexData")
                    if (hexData.size == 3) {
                        val fangXiang = HexDataParse.dataToUInt(listOf(hexData[0]))
                        when (fangXiang) {
                            1 -> {
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                when (index) { //1-Intensity ,2-Duration, 3-HZ
                                    1 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.nenfuHomeSeekBar1l, binding.nenfuHomeTv1l, num
                                        )
                                        Log.i(TAG, "IntensityL-- ${num}")
                                    }

                                    2 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.nenfuHomeSeekBar2l, binding.nenfuHomeTv2l, num
                                        )
                                        Log.i(TAG, "DurationL-- ${num}")
                                    }

                                    3 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.nenfuHomeSeekBar3l, binding.nenfuHomeTv3l, num
                                        )
                                        Log.i(TAG, "HZL-- ${num}")
                                    }
                                }
                            }

                            2 -> {
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                when (index) { //1-Intensity ,2-Duration, 3-HZ
                                    1 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.nenfuHomeSeekBar1R, binding.nenfuHomeTv1R, num
                                        )
                                        Log.i(TAG, "IntensityR-- ${num}")
                                    }

                                    2 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.nenfuHomeSeekBar2R, binding.nenfuHomeTv2R, num
                                        )
                                        Log.i(TAG, "DurationR-- ${num}")
                                    }

                                    3 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.nenfuHomeSeekBar3R, binding.nenfuHomeTv3R, num
                                        )
                                        Log.i(TAG, "HZR-- ${num}")
                                    }
                                }
                            }
                        }
                        Log.i(TAG, "fangxiang: $fangXiang")
                    }
                }

                KeyUtil.E9 -> { //指令9；01-待机、02-准备、03-输出
                    if (hexData.size == 2) {
                        val fangXiang = hexData[0]
                        val status = hexData[1] //状态
                        when (fangXiang) {
                            "01" -> {//左边  02-右边
                                when (status) { // 01/02/03(待机/准备/输出)
                                    "01" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.nenfuHomeClActionL,
                                                binding.nenfuHomeIvActionL, 1, "L"
                                            )
                                            receiveFlagL = 1
                                        }
                                    }

                                    "02" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.nenfuHomeClActionL,
                                                binding.nenfuHomeIvActionL, 2, "L"
                                            )
//                                            receiveFlagL = 2
                                        }
                                    }

                                    "03" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.nenfuHomeClActionL,
                                                binding.nenfuHomeIvActionL, 3, "L"
                                            )
                                            receiveFlagL = 3
                                        }
                                    }
                                }
                            }

                            "02" -> {
                                when (status) { // 01/02/03(待机/准备/输出)
                                    "01" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.nenfuHomeClActionR,
                                                binding.nenfuHomeIvActionR, 1, "R"
                                            )
                                            receiveFlagR = 1
                                        }
                                    }

                                    "02" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.nenfuHomeClActionR,
                                                binding.nenfuHomeIvActionR, 2, "R"
                                            )
//                                            receiveFlagR = 2
                                        }
                                    }

                                    "03" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.nenfuHomeClActionR,
                                                binding.nenfuHomeIvActionR, 3, "R"
                                            )
                                            receiveFlagR = 3
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                KeyUtil.F2 -> { //指令17：获取最大值最小值 (AA FF F2 05(长度) 01(方向) 05 8C(能量密度) 05 64(脉宽) EE)
                    if (hexData.size == 5) {
                        val fangXiang = HexDataParse.dataToUInt(listOf(hexData[0]))
                        when (fangXiang) {
                            1 -> {  //1左边 2右边
                                runOnUiThread {
                                    val minIntensity = HexDataParse.dataToUInt(listOf(hexData[1]))
                                    val maxIntensity = HexDataParse.dataToUInt(listOf(hexData[2]))
                                    val mineDuration = HexDataParse.dataToUInt(listOf(hexData[3]))
                                    val maxDuration = HexDataParse.dataToUInt(listOf(hexData[4]))
                                    seekBarMax1L = maxIntensity
                                    seekBarMin1L = minIntensity
                                    binding.nenfuHomeSeekBar1l.setMin(minIntensity)
                                    binding.nenfuHomeSeekBar1l.setMax(maxIntensity)
                                    seekBarMax2L = maxDuration
                                    seekBarMin2L = mineDuration
                                    binding.nenfuHomeSeekBar2l.setMin(mineDuration)
                                    binding.nenfuHomeSeekBar2l.setMax(maxDuration)
                                    Log.i(
                                        TAG,
                                        "左侧: ${minIntensity}--${maxIntensity}---${mineDuration}--${maxIntensity}"
                                    )
                                    initJianL()
                                    initJiaL()
                                }
                            }

                            2 -> {
                                runOnUiThread {
                                    val minIntensity = HexDataParse.dataToUInt(listOf(hexData[1]))
                                    val maxIntensity = HexDataParse.dataToUInt(listOf(hexData[2]))
                                    val mineDuration = HexDataParse.dataToUInt(listOf(hexData[3]))
                                    val maxDuration = HexDataParse.dataToUInt(listOf(hexData[4]))

                                    seekBarMax1R = maxIntensity
                                    seekBarMin1R = minIntensity
                                    binding.nenfuHomeSeekBar1l.setMin(minIntensity)
                                    binding.nenfuHomeSeekBar1R.setMax(maxIntensity)
                                    seekBarMax2R = maxDuration
                                    seekBarMin2R = mineDuration
                                    binding.nenfuHomeSeekBar2R.setMin(mineDuration)
                                    binding.nenfuHomeSeekBar2R.setMax(maxDuration)

                                    initJianR()
                                    initJiaR()
                                }
                            }
                        }
                    }
                }

                KeyUtil.EC -> { //指令12 接收4个报警参数，使用在工作页面最底部
                    if (hexData.size == 3) {
                        val fangXiang = HexDataParse.dataToUInt(listOf(hexData[0]))
                        when (fangXiang) {
                            1 -> {  //1左边 2右边
                                //01/02/03/04/05【水温 手柄头温度 水流量 水位】
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                //01-开启 00-关闭
                                val flag = HexDataParse.dataToUInt(listOf(hexData[2]))
                                when (flag) {
                                    0 -> {
                                        when (index) {
                                            1 -> {
                                                binding.nenfuHomeClWenDuL1.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.nenfuHomeTvWenDuL1.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            2 -> {
                                                binding.nenfuHomeClWenDuL2.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.nenfuHomeTvWenDuL2.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            3 -> {
                                                binding.nenfuHomeClWenDuL3.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.nenfuHomeTvWenDuL3.setTextColor(
                                                    ContextCompat.getColor(
                                                        this,
                                                        R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            4 -> {
                                                binding.nenfuHomeIvShuiWeiL.setImageResource(R.mipmap.icon_home_warning)
                                            }
                                        }
                                    }

                                    1 -> {// 1-开启
                                        when (index) {
                                            1 -> {
                                                binding.nenfuHomeClWenDuL1.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.nenfuHomeTvWenDuL1.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            2 -> {
                                                binding.nenfuHomeClWenDuL2.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.nenfuHomeTvWenDuL2.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            3 -> {
                                                binding.nenfuHomeClWenDuL3.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.nenfuHomeTvWenDuL3.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            4 -> {
                                                binding.nenfuHomeIvShuiWeiL.setImageResource(R.mipmap.icon_shui_liu_fc7c7c)
                                            }
                                        }
                                    }
                                }
                            }

                            2 -> {  //2右边
                                //01/02/03/04/05【水温 手柄头温度 水流量 水位】
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                //01-开启 00-关闭
                                val flag = HexDataParse.dataToUInt(listOf(hexData[2]))
                                when (flag) {
                                    0 -> {
                                        when (index) {
                                            1 -> {
                                                binding.nenfuHomeClWenDuR1.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.nenfuHomeTvWenDuR1.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            2 -> {
                                                binding.nenfuHomeClWenDuR2.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.nenfuHomeTvWenDuR2.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            3 -> {
                                                binding.nenfuHomeClWenDuR3.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.nenfuHomeTvWenDuR3.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            4 -> {
                                                binding.nenfuHomeIvShuiWeiR.setImageResource(R.mipmap.icon_home_warning)
                                            }
                                        }
                                    }

                                    1 -> {
                                        when (index) {
                                            1 -> {
                                                binding.nenfuHomeClWenDuR1.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.nenfuHomeTvWenDuR1.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            2 -> {
                                                binding.nenfuHomeClWenDuR2.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.nenfuHomeTvWenDuR2.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            3 -> {
                                                binding.nenfuHomeClWenDuR3.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.nenfuHomeTvWenDuR3.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            4 -> {
                                                binding.nenfuHomeIvShuiWeiR.setImageResource(R.mipmap.icon_shui_liu_fc7c7c)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                KeyUtil.EB -> {   //指令11 （接收4个参数，使用在工作页面最底部数字显示）
                    if (hexData.size == 3) {
                        val fangXiang = HexDataParse.dataToUInt(listOf(hexData[0]))
                        when (fangXiang) {
                            1 -> {  //1左边 2右边
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                val num = HexDataParse.hexByteToSignedInt(hexData[2])
                                runOnUiThread {
                                    when (index) {
                                        1 -> {
                                            binding.nenfuHomeTvWenDuL1.setText(num.toString())
                                        }

                                        2 -> {
                                            binding.nenfuHomeTvWenDuL2.setText(num.toString())
                                        }

                                        3 -> {
                                            binding.nenfuHomeTvWenDuL3.setText(num.toString())
                                        }

                                        4 -> {}
                                    }
                                }
                            }

                            2 -> {  //1左边 2右边
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                val num = HexDataParse.hexByteToSignedInt(hexData[2])
                                runOnUiThread {
                                    when (index) {
                                        1 -> {
                                            binding.nenfuHomeTvWenDuR1.setText(num.toString())
                                        }

                                        2 -> {
                                            binding.nenfuHomeTvWenDuR2.setText(num.toString())
                                        }

                                        3 -> {
                                            binding.nenfuHomeTvWenDuR3.setText(num.toString())
                                        }

                                        4 -> {}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initClick()
        BluetoothSocketManager.addDataReceivedListener(dataListener)
    }

    private fun initClick() {
        binding.nenfuHomeIvBack.setOnClickListener { finish() }

        binding.nenfuHomeSetting.setOnClickListener {
            val intent = Intent(this, MineActivity::class.java)
            startActivity(intent)
        }

        initJianL()
        initJiaL()

        initJianR()
        initJiaR()
        checkJiaJianClickDrable()

        //跳转用户列表MineActivity
        binding.nenfuHomeIvAvatarL.setOnClickListener {
            LiveEventBus.get<Boolean>(KeyUtil.NENFU_HOME_SELECT_USER).post(true)
            startActivity(Intent(this, MineActivity::class.java))
        }
        //跳转用户列表MineActivity
        binding.nenfuHomeIvAvatarR.setOnClickListener {
            LiveEventBus.get<Boolean>(KeyUtil.NENFU_HOME_SELECT_USER).post(false)
            startActivity(Intent(this, MineActivity::class.java))
        }

        //保存L
        binding.nenfuHomeLlSaveL.setOnClickListener {
            if (leftUserModel == null) {
                ToastUtils.show(getString(R.string.no_user_select))
                return@setOnClickListener
            }
            val l1Result = binding.nenfuHomeSeekBar1l.getProgress()
            val l2Result = binding.nenfuHomeSeekBar2l.getProgress()
            val l3Result = binding.nenfuHomeSeekBar3l.getProgress()

            SPUtil.put(KeyUtil.HOME_SEEKBAR_1_L, l1Result)
            SPUtil.put(KeyUtil.HOME_SEEKBAR_2_L, l2Result)
            SPUtil.put(KeyUtil.HOME_SEEKBAR_3_L, l3Result)
            CoreUtil.showIvCustomToast(
                binding.nenfuHomeIvSaveL,
                R.mipmap.icon_save_success_ffd754, R.mipmap.icon_save_ffd754
            )

            val leftData1 = binding.nenfuHomeSeekBar1l.getProgress()
            val leftData2 = binding.nenfuHomeSeekBar2l.getProgress()
            val leftData3 = binding.nenfuHomeSeekBar3l.getProgress()

            leftUserModel?.let {
                it.intensityValue = leftData1
                it.durationValue = leftData2
                it.FrequencyValue = leftData3
                UserRepository.updateUser(it)
            }
            Log.i(TAG, "保存-- ${Gson().toJson(leftUserModel)}")
        }

        //保存R
        binding.nenfuHomeLlSaveR.setOnClickListener {
            if (rightUserModel == null) {
                ToastUtils.show(getString(R.string.no_user_select))
                return@setOnClickListener
            }
            val r1Result = binding.nenfuHomeSeekBar1R.getProgress()
            val r2Result = binding.nenfuHomeSeekBar2R.getProgress()
            val r3Result = binding.nenfuHomeSeekBar3R.getProgress()

            SPUtil.put(KeyUtil.HOME_SEEKBAR_1_R, r1Result)
            SPUtil.put(KeyUtil.HOME_SEEKBAR_2_R, r2Result)
            SPUtil.put(KeyUtil.HOME_SEEKBAR_3_R, r3Result)
            CoreUtil.showIvCustomToast(
                binding.nenfuHomeIvSaveR,
                R.mipmap.icon_save_success_ffd754, R.mipmap.icon_save_ffd754
            )
            val rightData1 = binding.nenfuHomeSeekBar1R.getProgress()
            val rightData2 = binding.nenfuHomeSeekBar2R.getProgress()
            val rightData3 = binding.nenfuHomeSeekBar3R.getProgress()

            rightUserModel?.let {
                it.intensityValue = rightData1
                it.durationValue = rightData2
                it.FrequencyValue = rightData3
                UserRepository.updateUser(it)
            }
            Log.i(TAG, "保存-- ${Gson().toJson(leftUserModel)}")
        }

        //开始按钮L
        binding.nenfuHomeClActionL.setOnClickListener {
            when (actionFlagL) {
                0 -> {
                    binding.nenfuHomeIvActionL.setImageResource(R.mipmap.icon_pause)
                    actionFlagL = 1
                }

                1 -> {
                    binding.nenfuHomeIvActionL.setImageResource(R.mipmap.icon_home_pause)
                    actionFlagL = 0
                }
            }
            sendActionFlag("L", actionFlagL)
        }

        //开始按钮R
        binding.nenfuHomeClActionR.setOnClickListener {
            when (actionFlagR) {
                0 -> {
                    binding.nenfuHomeIvActionR.setImageResource(R.mipmap.icon_pause)
                    actionFlagR = 1
                }

                1 -> {
                    binding.nenfuHomeIvActionR.setImageResource(R.mipmap.icon_home_pause)
                    actionFlagR = 0
                }
            }
            sendActionFlag("R", actionFlagR)
        }

        LiveEventBus.get<Map<Int, SelectModel>>(KeyUtil.TO_NENFU_HOME_ACTIVITY)
            .observeSticky(this, {
                it[0]?.let { lResult ->
                    when (lResult.location) {
                        0 -> {
                            binding.nenfuHomeTvLocationL.text = getString(R.string.face)
                        }

                        1 -> {
                            binding.nenfuHomeTvLocationL.text = getString(R.string.Arms)
                        }

                        2 -> {
                            binding.nenfuHomeTvLocationL.text = getString(R.string.chest)
                        }

                        3 -> {
                            binding.nenfuHomeTvLocationL.text = getString(R.string.back)
                        }

                        4 -> {
                            binding.nenfuHomeTvLocationL.text = getString(R.string.Abdomen)
                        }

                        5 -> {
                            binding.nenfuHomeTvLocationL.text = getString(R.string.Legs)
                        }
                    }
                }
                it[1]?.let { rResult ->
                    when (rResult.location) {
                        0 -> {
                            binding.nenfuHomeTvLocationR.text = getString(R.string.face)
                        }

                        1 -> {
                            binding.nenfuHomeTvLocationR.text = getString(R.string.Arms)
                        }

                        2 -> {
                            binding.nenfuHomeTvLocationR.text = getString(R.string.chest)
                        }

                        3 -> {
                            binding.nenfuHomeTvLocationR.text = getString(R.string.back)
                        }

                        4 -> {
                            binding.nenfuHomeTvLocationR.text = getString(R.string.Abdomen)
                        }

                        5 -> {
                            binding.nenfuHomeTvLocationR.text = getString(R.string.Legs)
                        }
                    }
                }
            })

        //接收用户列表返回的数据
        LiveEventBus.get<Map<Boolean, UserModel>>(KeyUtil.NENFU_HOME_SELECT_USER_VALUE)
            .observeSticky(this, { map ->
                if (map != null) {
                    map[true]?.let {    //左侧手柄
                        leftUserModel = it
                        binding.nenfuHomeTvNameL.text = it.name
                        binding.nenfuHomeTvPhoneL.text = it.phone
                        if (it.intensityValue != null && it.intensityValue!! > 0) {
                            setSeekBarValue1L(it.intensityValue!!)
                        }
                        if (it.durationValue != null && it.durationValue!! > 0) {
                            setSeekBarValue2L(it.durationValue!!)
                        }

                        if (it.FrequencyValue != null && it.FrequencyValue!! > 0) {
                            setSeekBarValue3L(it.FrequencyValue!!)
                        }

                        if (it.intensityValue != null && it.durationValue != null && it.FrequencyValue != null) {
                            sendUserValue(
                                "L", it.intensityValue!!, it.durationValue!!, it.FrequencyValue!!
                            )
                        }
                    }

                    map[false]?.let {    //右侧手柄
                        rightUserModel = it
                        binding.nenfuHomeTvNameR.text = it.name
                        binding.nenfuHomeTvPhoneR.text = it.phone
                        if (it.intensityValue != null && it.intensityValue!! > 0) {
                            setSeekBarValue1R(it.intensityValue!!)
                        }
                        if (it.durationValue != null && it.durationValue!! > 0) {
                            setSeekBarValue2R(it.durationValue!!)
                        }

                        if (it.FrequencyValue != null && it.FrequencyValue!! > 0) {
                            setSeekBarValue3R(it.FrequencyValue!!)
                        }
                        if (it.intensityValue != null && it.durationValue != null && it.FrequencyValue != null) {
                            sendUserValue(
                                "R", it.intensityValue!!, it.durationValue!!, it.FrequencyValue!!
                            )
                        }
                    }
                }
            })

        binding.nenfuHomeSeekBar1l.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.nenfuHomeTv1l.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.nenfuHomeSeekBar2l.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.nenfuHomeTv2l.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.nenfuHomeSeekBar3l.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.nenfuHomeTv3l.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.nenfuHomeSeekBar1R.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.nenfuHomeTv1R.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.nenfuHomeSeekBar2R.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.nenfuHomeTv2R.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.nenfuHomeSeekBar3R.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.nenfuHomeTv3R.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })
    }

    private fun setSeekBarValue1L(value1: Int) {
        binding.nenfuHomeSeekBar1l.setProgress(value1)
        binding.nenfuHomeTv1l.setText(value1.toString())
    }

    private fun setSeekBarValue2L(value2: Int) {
        binding.nenfuHomeSeekBar2l.setProgress(value2)
        binding.nenfuHomeTv2l.setText(value2.toString())
    }

    private fun setSeekBarValue3L(value3: Int) {
        binding.nenfuHomeSeekBar3l.setProgress(value3)
        binding.nenfuHomeTv3l.setText(value3.toString())
    }

    private fun setSeekBarValue1R(value1: Int) {
        binding.nenfuHomeSeekBar1R.setProgress(value1)
        binding.nenfuHomeTv1R.setText(value1.toString())
    }

    private fun setSeekBarValue2R(value2: Int) {
        binding.nenfuHomeSeekBar2R.setProgress(value2)
        binding.nenfuHomeTv1R.setText(value2.toString())
    }

    private fun setSeekBarValue3R(value3: Int) {
        binding.nenfuHomeSeekBar3R.setProgress(value3)
        binding.nenfuHomeTv3R.setText(value3.toString())
    }

    //加加
    private fun initJiaR() {
        bindSimpleStepButton(
            "R", 21, binding.nenfuHomeClJia1R, binding.nenfuHomeSeekBar1R, binding.nenfuHomeTv1R,
            true, max = seekBarMax1R, min = seekBarMin1R
        )
        bindSimpleStepButton(
            "R", 22, binding.nenfuHomeClJia2R, binding.nenfuHomeSeekBar2R, binding.nenfuHomeTv2R,
            true, max = seekBarMax2R, min = seekBarMin2R
        )
        bindSimpleStepButton(
            "R", 23, binding.nenfuHomeClJia3R, binding.nenfuHomeSeekBar3R, binding.nenfuHomeTv3R,
            true, max = seekBarMax3R, min = seekBarMin3R
        )
    }

    private fun initJianR() {
        binding.nenfuHomeClJian1R.setOnClickListener {
            bindSimpleStepButton(
                "R",
                11,
                binding.nenfuHomeClJian1R,
                binding.nenfuHomeSeekBar1R,
                binding.nenfuHomeTv1R,
                false,
                max = seekBarMax1R,
                min = seekBarMin1R
            )
        }
        binding.nenfuHomeClJian2R.setOnClickListener {
            bindSimpleStepButton(
                "R",
                12,
                binding.nenfuHomeClJian2R,
                binding.nenfuHomeSeekBar2R,
                binding.nenfuHomeTv2R,
                false,
                max = seekBarMax2R,
                min = seekBarMin2R
            )
        }
        binding.nenfuHomeClJian3R.setOnClickListener {
            bindSimpleStepButton(
                "R",
                13,
                binding.nenfuHomeClJian3R,
                binding.nenfuHomeSeekBar3R,
                binding.nenfuHomeTv3R,
                false,
                max = seekBarMax3R,
                min = seekBarMin3R
            )
        }
    }

    //加加
    private fun initJiaL() {
        bindSimpleStepButton(
            "L", 21, binding.nenfuHomeClJia1L, binding.nenfuHomeSeekBar1l, binding.nenfuHomeTv1l,
            true, max = seekBarMax1L, min = seekBarMin1L
        )
        bindSimpleStepButton(
            "L", 22, binding.nenfuHomeClJia2L, binding.nenfuHomeSeekBar2l, binding.nenfuHomeTv2l,
            true, max = seekBarMax2L, min = seekBarMin2L
        )
        bindSimpleStepButton(
            "L", 23, binding.nenfuHomeClJia3L, binding.nenfuHomeSeekBar3l, binding.nenfuHomeTv3l,
            true, max = seekBarMax3L, min = seekBarMin3L
        )
    }

    private fun initJianL() {
        bindSimpleStepButton(
            "L", 11, binding.nenfuHomeClJian1L, binding.nenfuHomeSeekBar1l, binding.nenfuHomeTv1l,
            false, max = seekBarMax1L, min = seekBarMin1L
        )
        bindSimpleStepButton(
            "L", 12, binding.nenfuHomeClJian2L, binding.nenfuHomeSeekBar2l, binding.nenfuHomeTv2l,
            false, max = seekBarMax1L, min = seekBarMin1L
        )
        bindSimpleStepButton(
            "L", 13, binding.nenfuHomeClJian3L, binding.nenfuHomeSeekBar3l, binding.nenfuHomeTv3l,
            false, max = seekBarMax1L, min = seekBarMin1L
        )
    }

    //点击加减的按钮有个动效
    private fun checkJiaJianClickDrable() {
        setTouchFeedback(binding.nenfuHomeClJian1L)
        setTouchFeedback(binding.nenfuHomeClJian2L)
        setTouchFeedback(binding.nenfuHomeClJian3L)
        setTouchFeedback(binding.nenfuHomeClJian1R)
        setTouchFeedback(binding.nenfuHomeClJian2R)
        setTouchFeedback(binding.nenfuHomeClJian3R)

        setTouchFeedback(binding.nenfuHomeClJia1L)
        setTouchFeedback(binding.nenfuHomeClJia2L)
        setTouchFeedback(binding.nenfuHomeClJia3L)
        setTouchFeedback(binding.nenfuHomeClJia1R)
        setTouchFeedback(binding.nenfuHomeClJia2R)
        setTouchFeedback(binding.nenfuHomeClJia3R)
    }

    private fun setTouchFeedback(touchTarget: View) {
        touchTarget.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    touchTarget.setBackgroundResource(R.drawable.ffd754_button_click)
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    touchTarget.setBackgroundResource(R.drawable.shape_circle_ffd754)
                }
            }
            false
        }
    }

    private fun bindSimpleStepButton(
        fangxiang: String, index: Int, button: View, seekBar: HalfCircleSeekBar, textView: TextView,
        isIncrement: Boolean, step: Int = 1, min: Int, max: Int
    ) {
        button.setOnClickListener {
            var buttonCommand = ""
            when (fangxiang) {
                "L" -> {
                    when (index) {
                        11 -> {
                            buttonCommand = "01 " + "01 " + "01"
                        }

                        12 -> {
                            buttonCommand = "01 " + "02 " + "01"
                        }

                        13 -> {
                            buttonCommand = "01 " + "03 " + "01"
                        }

                        21 -> {
                            buttonCommand = "01 " + "01 " + "02"
                        }

                        22 -> {
                            buttonCommand = "01 " + "02 " + "02"
                        }

                        23 -> {
                            buttonCommand = "01 " + "03 " + "02"
                        }
                    }
                }

                "R" -> {
                    when (index) {
                        11 -> {
                            buttonCommand = "02 " + "01 " + "01"
                        }

                        12 -> {
                            buttonCommand = "02 " + "02 " + "01"
                        }

                        13 -> {
                            buttonCommand = "02 " + "03 " + "01"
                        }

                        21 -> {
                            buttonCommand = "02 " + "01 " + "02"
                        }

                        22 -> {
                            buttonCommand = "02 " + "02 " + "02"
                        }

                        23 -> {
                            buttonCommand = "02 " + "03 " + "02"
                        }
                    }
                }
            }
            //点击不主动改变事件，等后台返回数据改变
            /*val current = seekBar.getProgress()
            val newVal = when {
                isIncrement -> (current + step).coerceAtMost(max)
                else -> (current - step).coerceAtLeast(min)
            }
            seekBar.setProgress(newVal)
            textView.text = newVal.toString()*/

            val buttonCommandAll = KeyUtil.HOME_BUTTON_CLICK_COMMAND + buttonCommand + KeyUtil.EE
            val data = HexConverter.hexStringToByteArray(buttonCommandAll)
            Log.i(TAG, "加减的命令-- $buttonCommandAll")
            BluetoothSocketManager.send(data)
        }
    }

    private fun sendUserValue(fangXiang: String, value1: Int, value2: Int, value3: Int) {
        var mFangXiang = ""
        when (fangXiang) {
            "L" -> {
                mFangXiang = "01 "
            }

            "R" -> {
                mFangXiang = "02 "
            }
        }
        if (mFangXiang.isEmpty()) {
            return
        }
        val data1 = HexConverter.intTo2ByteHex(value1)
        val value1Hex = data1.joinToString(" ") { "%02X".format(it) }

        val data2 = HexConverter.intTo2ByteHex(value2)
        val value2Hex = data2.joinToString(" ") { "%02X".format(it) }

        val data3 = HexConverter.intTo1ByteHex(value3)
        val value3Hex = data3.joinToString(" ") { "%02X".format(it) }

        val commandAll =
            KeyUtil.USER_ITEM_VALUE_COMMAND + mFangXiang + value1Hex + " " + value2Hex + " " + value3Hex + KeyUtil.EE
        val data = HexConverter.hexStringToByteArray(commandAll)
        Log.i(TAG, "用户数据-- $commandAll")
        BluetoothSocketManager.send(data)
    }

    /**
     * 待机/准备
     * @param flag 1-待机 , 2-准备
     */
    private fun sendActionFlag(fangXiang: String, flag: Int) {
        var mFangXiang = ""
        when (fangXiang) {
            "L" -> {
                mFangXiang = "01 "
            }

            "R" -> {
                mFangXiang = "02 "
            }
        }
        val mFlag = when (flag) {
            0 -> "1 "
            1 -> "2 "
            else -> "0 " // 或者根据需求处理其他情况
        }
        val commandAll =
            KeyUtil.HOME_ACTION_FLAG + mFangXiang + "0" + mFlag + KeyUtil.EE
        Log.i(TAG, "启动还是准备--: $commandAll")
        val data = HexConverter.hexStringToByteArray(commandAll)
        BluetoothSocketManager.send(data)
    }

    /**
     * @param temp 1/2/3(待机/准备/输出)
     */
    private fun setupPlayButton(
        container: ConstraintLayout, iconView: AppCompatImageView, temp: Int, fangXiang: String
    ) {
        // 确保背景是 GradientDrawable（圆形）
        val backgroundDrawable = container.background
        if (backgroundDrawable !is GradientDrawable) {
            val circleDrawable = GradientDrawable()
            circleDrawable.shape = GradientDrawable.OVAL
            circleDrawable.setColor(ContextCompat.getColor(container.context, R.color.color_FFD754))
            container.background = circleDrawable
        }

        // 如果有旧动画，先停止
        breathingAnimators[container]?.let { animator ->
            animator.cancel()
            breathingAnimators.remove(container)
        }

        when (temp) {
            1 -> { // 待机
                (container.background as? GradientDrawable)?.setColor(
                    ContextCompat.getColor(container.context, R.color.color_FFD754)
                ) ?: run {
                    container.setBackgroundResource(R.drawable.shape_circle_ffd754_shi)
                }
                iconView.setImageResource(R.mipmap.icon_home_pause)

                //待机状态下就暂停计时
                onPauseCommand(fangXiang)
            }

            2 -> { // 准备
                (container.background as? GradientDrawable)?.setColor(
                    ContextCompat.getColor(container.context, R.color.color_FFD754)
                ) ?: run {
                    container.setBackgroundResource(R.drawable.shape_circle_ffd754_shi)
                }
                iconView.setImageResource(R.mipmap.icon_pause)

                when (fangXiang) {
                    "L" -> {
                        if (receiveFlagL == 3) {    //上次是输出状态
                            //发送指令
                            sendCountIndex(mWorkCountL, "L")
                            //更新日期和次数
                            leftUserModel?.let {
                                it.treatmentDate = CoreUtil.getCurrentDateWithSimpleDateFormat()
                                //次数
                                val currentIndex =
                                    if (it.treatmentTimes == null) 0 else it.treatmentTimes
                                it.treatmentTimes = currentIndex!! + 1
                                UserRepository.updateUser(it)
                            }
                        }
                    }

                    "R" -> {
                        if (receiveFlagR == 3) {    //上次是输出状态
                            //发送指令
                            sendCountIndex(mWorkCountR, "R")
                            //更新日期和次数
                            rightUserModel?.let {
                                it.treatmentDate = CoreUtil.getCurrentDateWithSimpleDateFormat()
                                //次数
                                val currentIndex =
                                    if (it.treatmentTimes == null) 0 else it.treatmentTimes
                                it.treatmentTimes = currentIndex!! + 1
                                UserRepository.updateUser(it)
                            }
                        }
                    }
                }
                //准备状态下开始发送计时命令
                onStartCommand(fangXiang)
            }

            3 -> { // 输出 -> 开启呼吸动画
                val breathingAnimator = ValueAnimator.ofArgb(
                    ContextCompat.getColor(container.context, R.color.color_FFD754),
                    Color.parseColor("#88fc7c7c")
                ).apply {
                    duration = 1000L
                    repeatCount = ValueAnimator.INFINITE
                    repeatMode = ValueAnimator.REVERSE
                    addUpdateListener { animator ->
                        val color = animator.animatedValue as Int
                        (container.background as GradientDrawable).setColor(color)
                    }
                    start()
                }
                breathingAnimators[container] = breathingAnimator
                iconView.setImageResource(R.mipmap.icon_pause)
            }
        }
    }

    //设置当前的值（点击加减按钮后有后台返回的数值显示上去）
    private fun setSeekbarValue(
        seekBarProgress: HalfCircleSeekBar, textView: AppCompatTextView, value: Int
    ) {
        runOnUiThread {
            seekBarProgress.setProgress(value)
            textView.setText(value.toString())
        }
    }

    //倒计时开始
    private fun onStartCommand(key: String) {
        val controller = controllers[key]
        if (controller == null) {
            val newController = WorkTimerController(
                when (key) {
                    "L" -> binding.nenfuHomeSeekBar3l.getProgress()
                    "R" -> binding.nenfuHomeSeekBar3R.getProgress()
                    else -> {
                        0
                    }
                },
                when (key) {
                    "L" -> if (SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_L) == null) 0
                    else SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_L)!!

                    "R" -> if (SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_R) == null) 0
                    else SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_R)!!

                    else -> {
                        0
                    }
                },
                onSendCommand = { mCount -> //每到一分钟就发送一次
                    Log.i(TAG, "运行的次数-- " + mCount + " -方向：" + key)
                    //存储到本地，到设置页面时候可以显示过去
                    when (key) {
                        "L" -> {
                            mWorkCountL = mCount
                            SPUtil.put(KeyUtil.HANDLE_SEND_COUNT_ALL_L, mCount)
                        }

                        "R" -> {
                            mWorkCountR = mCount
                            SPUtil.put(KeyUtil.HANDLE_SEND_COUNT_ALL_R, mCount)
                        }
                    }
                },
                onFinish = {
//                    ImageDialogShow().showing(supportFragmentManager, key, 0)
                })
            controllers[key] = newController
            newController.start()
        } else {
            controller.start() // 已存在的，继续运行
        }
    }

    /**
     * 发送手柄累计的运行次数
     */
    private fun sendCountIndex(mCount: Int, key: String) {
        val hexCount = HexDataParse.intToFixed4ByteHex(mCount)
        val value = HexConverter.hexListToSpacedString(hexCount)
        val commandAll =
            KeyUtil.SEND_TIMER_COUNT_ALL + when (key) {
                "L" -> "01"
                "R" -> "02"
                else -> "00"
            } + " " + value + " " + KeyUtil.EE
        val data = HexConverter.hexStringToByteArray(commandAll)
        Log.i(TAG, "发送计时的指令--: $commandAll")
        BluetoothSocketManager.send(data)
    }

    //倒计时暂停
    private fun onPauseCommand(key: String) {
        controllers[key]?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 避免内存泄漏或多次回调
        BluetoothSocketManager.removeDataReceivedListener(dataListener)
    }
}